;(function ($,window,document,undefined ){
	//配置参数
	var defaults = {
		success:null,
		bl:null,
		callback:function(){}	//回调
	};
	
	var Repair = function(element,options){
		//全局变量
		var opts = options,//配置
			$document = $(document),
			$obj = $(element);//容器

		this.success = function(){
			return opts.success;
		}
		
		//绑定事件
		this.filling = function(opts){
            $obj.addClass('score');
			$obj.iziModal({
			    title: '报修',
                headerColor: '#fff',
			    theme: '',  // light
			    attached: '', // bottom, top
			    icon: null,
			    iconText: null,
			    iconColor: '',
			    rtl: false,
			    width: 600,
			    padding: 0,
                radius: 0.4 * rem,
			    zindex: 10050,
			    iframe: false,
			    iframeHeight: 400,
			    iframeURL: null,
			    focusInput: false,
			    group: '',
			    loop: false,
			    navigateCaption: true,
			    navigateArrows: true, // closeToModal, closeScreenEdge
			    history: true,
			    restoreDefaultContent: false,
			    autoOpen: true, // Boolean, Number
			    bodyOverflow: false,
			    fullscreen: true,
			    openFullscreen: false,
			    closeOnEscape: false,
			    overlay: true,
			    overlayClose: false,
			    overlayColor: 'rgba(0, 0, 0, 0.4)',
			    timeout: false,
			    timeoutProgressbar: false,
			    pauseOnHover: false,
			    timeoutProgressbarColor: 'rgba(255,255,255,0.5)',
			    transitionIn: 'comingIn',
			    transitionOut: 'comingOut',
			    transitionInOverlay: 'fadeIn',
			    transitionOutOverlay: 'fadeOut',
			    onFullscreen: function(){},
			    onResize: function(){
			    	//$obj.iziModal('recalculateLayout');
			    },
			    onOpening: function(){},
			    onOpened: function(){
			    	//$("#maintenanceTyp").select2({language:"zh-CN",allowClear:true,minimumResultsForSearch: Infinity});
                    initEmergencyDegree();

			    },
			    onClosing: function(){},
			    onClosed: function(){
			        $obj.remove();
                    if (!$('#iziModal-repair').length) {
                        $('body').append('<div id="iziModal-repair"></div>');
                    }
			    }
			});
			var html = '<div class="box-body">'
					 +		'<form class="form-horizontal" id="addRepairFrom" method="post" enctype="multipart/form-data">'
					 +			'<div class="contact-content hide">'
					 +				'<div class="form-group">'
					 +					'<label class="col-sm-12 text-info text-muted">合同信息</label>'
					 +      		'</div>'
					 +				'<div class="form-group col-sm-12">'
				     +					'<label class="col-sm-2 control-label text-muted">合同号</label>'
				     +					'<div class="col-sm-10" style="margin-top: 5px;">'
				     +						'<a id="contact-number" style="cursor: pointer" target="_blank"></a>'
				     +					'</div>'
				     +				'</div>'
					 +				'<div class="form-group col-sm-12">'
				     +					'<label class="col-sm-2 control-label text-muted">联系人</label>'
				     +					'<div class="col-sm-10" style="margin-top: 5px;">'
				     +						'<span id="contact-person"></span>'
				     +					'</div>'
				     +				'</div>'
				     +				'<div class="form-group col-sm-12">'
				     +					'<label class="col-sm-2 control-label text-muted">联系电话</label>'
				     +					'<div class="col-sm-10" style="margin-top: 5px;">'
				     +						'<span id="contact-phone"></span>'
				     +					'</div>'
				     +				'</div>'
				     +				'<div class="form-group col-sm-12">'
				     +					'<label class="col-sm-2 control-label text-muted">维修商</label>'
				     +					'<div class="col-sm-10" style="margin-top: 5px;">'
				     +						'<span id="service-provide"></span>'
				     +					'</div>'
				     +				'</div>'
				     +			'</div>'
				  	 +			'<div class="form-group">'
					 +				'<label class="col-sm-4 text-info text-muted">报修信息</label>'
					 +      	'</div>'
					 +			'<div class="form-group hide">'
				     +				'<label for="deviceId" class="col-sm-2 control-label text-muted">ID</label>'
				     +				'<div class="col-sm-10">'
				     +					'<input type="text" class="form-control" id="deviceId" name="deviceId" value="'+opts.deviceId+'">'
				     +				'</div>'
				     +			'</div>'
					 +			'<div class="form-group hide">'
					 +				'<label for="deviceId" class="col-sm-2 control-label text-muted">合同ID</label>'
					 +				'<div class="col-sm-10">'
					 +					'<input type="text" class="form-control" id="contractInfoId" name="contractInfoId">'
					 +				'</div>'
					 +			'</div>'
				     +			'<div class="form-group">'
				     +				'<label for="assetsName1" class="col-sm-2 control-label text-muted">设备名称<span class="text-red"> *</span></label>'
				     +				'<div class="col-sm-10">'
				     +					'<input type="text" class="form-control" id="assetsName1" readonly="readonly" value="'+opts.deviceName+'">'
				     +				'</div>'
				     +			'</div>'
				     +			'<div class="form-group">'
				     +				'<label for="assetsNo" class="col-sm-2 control-label text-muted">资产编号<span class="text-red"> *</span></label>'
				     +				'<div class="col-sm-10">'
				     +					'<input type="text" class="form-control" id="assetsNo" readonly="readonly" value="'+opts.assetsNo+'">'
				     +				'</div>'
				     +			'</div>'
					 +			'<div class="form-group">'
					 +				'<label for="attachment" class="col-sm-2 control-label text-muted">附件</label>'
					 +				'<div class="col-sm-10">'
					 +					'<input type="text" class="form-control" id="attachment">'
					 /*+					'<select class="form-control" id="attachment">'
					 +					'</select>'*/
					 +				'</div>'
					 +			'</div>'
					 +			'<div class="form-group">'
				     +				'<label for="id" class="col-sm-2 control-label text-muted">故障时间<span class="text-red"> *</span></label>'
				     +				'<div class="col-sm-10">'
				     +					'<input type="text" class="form-control" id="faultTime1" name="faultTime" placeholder="" autocomplete="off">'
				     +				'</div>'
				     +			'</div>'
					+			'<div class="form-group">'
					+				'<label for="id" class="col-sm-2 control-label text-muted">紧急程度<span class="text-red"> *</span></label>'
					+				'<div class="col-sm-10">'
					+					'<select class="form-control" id="emergencyDegree" name="emergencyDegree" style="width: 100%;"> </select>'
					+				'</div>'
					+			'</div>'
				     +			'<div class="form-group">'
				     +				'<label for="assetsStatus" class="col-sm-2 control-label text-muted">设备状态<span class="text-red"> *</span></label>'
				     +				'<div class="col-sm-10">'
				     +					'<div class="radio">'
				     +						'<label><input type="radio" class="flat-green" value="1" name="assetsStatus">&nbsp;正常&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>'
				     +						'<label><input type="radio" class="flat-green" checked="checked" name="assetsStatus" value="2">&nbsp;故障&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>'
				     +						'<label><input type="radio" class="flat-green" name="assetsStatus" value="3">&nbsp;宕机</label>'
				     +				'	</div>'
				     +				'</div>'
				     +			'</div>'
				     +			'<div class="form-group">'
				     +				'<label for="fault" class="col-sm-2 control-label text-muted">故障描述</label>'
				     +				'<div class="col-sm-10">'
				     +					'<textarea class="form-control" id="fault" name="fault"></textarea>'
				     +				'</div>'
				     +			'</div>'
				     +			'<div class="form-group">'
				     +				'<label class="col-sm-2 control-label text-muted">故障图片<span class="text-red"> &nbsp;&nbsp;&nbsp;</span></label>'
				     +				'<div class="col-sm-10" id="fileinfo">'
				     +					'<input type="file" class="file" multiple name="files" id="files">'
				     +				'</div>'
				     +			'</div>'
				     +			'<div class="box-footer text-right" style="padding-right:10px;">'
				     +				'<button type="button" class="btn btn-default cancel" data-izimodal-close style="margin-right:5px">取消</button>'
				     +				'<button name="save" id="save" type="button" class="btn bg-aqua save" data-loading-text="保存中...">保存</button>'
				     +			'</div>'
					 +		'</form>'
					 +		'<form class="form-horizontal hide" id="addAssignFrom" method="post" enctype="multipart/form-data">'
					 +			'<input type="text" class="form-control" id="repair-id" name="id">'
				     +			'<input type="text" class="form-control" id="service-provide-id" name="serviceProviderId">'
				     +			'<input type="text" class="form-control" id="maintenance-type" name="maintenanceType" value="0">'
				     +			'<input type="text" class="form-control" id="repair-type" name="repairType" value="5002">'
				     +			'<input type="file" class="file" name="files" id="files-upload">'
					 +		'</form>'
					 + '</div>'
                     + '<style>#iziModal-repair .select2-container .select2-selection--single{height: 34px;}#iziModal-repair .select2-container--default .select2-selection--single .select2-selection__rendered{line-height:34px;}#iziModal-repair .select2 {margin: 5px 0;}#iziModal-repair .select2-container--default .select2-selection--single{background: #f5f5f5;}</style>';
			$obj.find(".iziModal-content").html(html);

			$('#files').fileinput({
				language: 'zh', //设置语言
				enctype: 'multipart/form-data',
				showUpload: false, //是否显示上传按钮
				showCaption: false,	//是否显示标题
				browseClass: "btn btn-info", //按钮样式
				maxFileCount:5,	//允许同时上传的最大文件个数
				//allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
				msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
			});
			
			// 初始化校验
			$('#addRepairFrom').bootstrapValidator({
		        excluded: [':disabled', ':hidden', ':not(:visible)'],
		        live: 'enabled',
		        message: '非有效值',
		        fields: {
		        	faultTime:{
		                validators: {
		                	notEmpty: {
		                        message: '故障时间不能为空'
		                    }
		                }
		            }
		        }
		    });
            // 查询合同信息
            $.ajax({
                url: basePath + '/parameter/contract/getContractInfo',
                data: {assetsId: opts.deviceId},
                type: 'POST',
                success:function(data){
                    if(data.ret){
                        if(data.data){
                            $obj.find(".contact-content").removeClass("hide");
                            $obj.find("#contact-number").text(data.data.contractNo || '');
                            $obj.find("#contact-number").attr("href","../contract/queryContractInfoById?id="+data.data.id);
                            $obj.find("#contact-person").text(data.data.contactPerson || '');
                            $obj.find("#contact-phone").text(data.data.contactPhone || '');
                            $obj.find("#service-provide").text(data.data.secondParty || '');
                            $obj.find("#contractInfoId").val(data.data.id);
                            $obj.find("#service-provide-id").val(data.data.serviceProviderId);
                        }else{
                            $obj.find(".contact-content").addClass("hide");
                        }
                    }
                },
            })

			function initEmergencyDegree(){
                $("#emergencyDegree").html("");
                $.ajax({
                    type : "POST",
                    url : basePath + "/parameter/base/queryItem",
                    data :{'type':'emergency_degree'},//整个表单提交
                    dataType : "json",
                    success : function(data) {
                        var str = "";
                        $.each(data.data,function(index,item){
                            str += "<option value='"+item.id+"'>"+item.item+"</option>";
                        })
                        $("#emergencyDegree").html(str);
                        $("#emergencyDegree").select2({language:"zh-CN",placeholder: "请选择紧急程度",allowClear: true,minimumResultsForSearch: -1});
                        $("#emergencyDegree").val(6011).trigger("change");
                    }
                });
			}
			
			// 初始化故障时间
			$("#faultTime1").datetimepicker({
				todayHighlight:true,	// 当前时间高亮显示
				autoclose:true,
				endDate:new Date(),		// 选择日期不能超过当前日期
				todayBtn:true,			// 底部显示今天按钮
				minuteStep:1,
				language:'zh-CN',
				upkeepDate : new Date()  
					}).on('hide',function(e) {  
			            $('#addRepairFrom').data('bootstrapValidator')  
			                .updateStatus('faultTime', 'NOT_VALIDATED',null)  
			                .validateField('faultTime');
		    });
			
			$(".fileinput-upload-button").hide();
			$(".file-drop-zone-title").html("");
			
			// 初始化单选款
			$('input[type="radio"].flat-green').iCheck({
				  checkboxClass: 'icheckbox_flat-blue',
				  radioClass: 'iradio_flat-blue'
			});
			
		}
		
		//绑定事件
		this.eventBind = function(){
			var self = this;
			//必须先解绑再绑定事件，否则多次执行后会多次触发
			$obj.find('button[name="save"]').click(function(){
				if(!opts.bl){
					$('#addRepairFrom').bootstrapValidator('validate');
					if($('#addRepairFrom').data('bootstrapValidator').isValid()){
						var formData = new FormData($("#addRepairFrom")[0]);
						formData.append('parameterEventResultId', opts.parameterEventResultId);
						console.log(formData.get('files'));
                        opts.bl = true;
						$.ajax({
							type : "POST",
							url : basePath + "/parameter/repair/addRepair",
						 	data :formData,//整个表单提交
							dataType : "json",
						 	async: false,  
				            cache: false,  
				            contentType: false,
				            processData: false, 
							success : function(data) {
								try {
									if (data.ret == 1) {
										if($("#contractInfoId").val()){
											$("#repair-id").val(data.repairId);
											var assignFormData = new FormData($("#addAssignFrom")[0]);
											$.ajax({
												url:basePath + '/parameter/repair/addDispatchInfo',
												type:'POST',
												data: assignFormData,
												dataType: "json",
											 	async: false,  
									            cache: false,  
									            contentType: false,
									            processData: false, 
												success: function(data){
													console.log(data);
												},
												failure: function(data){
													console.log(data);
												}
											})
											new $.flavr({content:data.msg,closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'success',action:function(){}}]});
											$("#queryForm").submit();
										}else{
											new $.flavr({content:data.msg,closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'success',action:function(){}}]});
											$("#queryForm").submit();
										}
									} else {
										new $.flavr({content:data.msg,closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'danger',action:function(){}}]});
										//如果成功，则调用指派工程师接口
									}
								} catch (error) {
									new $.flavr({content:"操作遇到问题",closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'danger',action:function(){}}]});
								}
								$obj.iziModal('close');
								typeof opts.callback === 'function' && opts.callback(self);
							},
                            failure : function() {
								$obj.iziModal('close');
							}
						});
					}
				}
			});
		}
		
		//初始化
		this.init = function(){
			this.filling(opts);
			this.eventBind();
		};
		this.init();
	}
	
	$.fn.repair = function(parameter,callback){
		if(typeof parameter == 'function'){//重载
			callback = parameter;
			parameter = {};
		}else{
			parameter = parameter || {};
			callback = callback || function(){};
		}
		var options = $.extend({},defaults,parameter);
		callback(new Repair(this, options));
	};
})(jQuery, window,document);